import { useCallback, useRef, useEffect } from 'react'

// 性能指标类型
const METRIC_TYPES = {
  RENDER_TIME: 'render_time',
  API_RESPONSE_TIME: 'api_response_time',
  IMAGE_LOAD_TIME: 'image_load_time',
  USER_INTERACTION: 'user_interaction',
  MEMORY_USAGE: 'memory_usage'
}

// 性能监控配置
const MONITOR_CONFIG = {
  // 是否启用性能监控
  ENABLED: process.env.NODE_ENV === 'development',
  // 最大记录数
  MAX_RECORDS: 100,
  // 上报间隔（毫秒）
  REPORT_INTERVAL: 30000
}

// 性能数据存储
const performanceData = {
  metrics: [],
  startTime: Date.now()
}

// 性能监控类
class PerformanceMonitor {
  constructor() {
    this.metrics = []
    this.startTime = Date.now()
    this.isEnabled = MONITOR_CONFIG.ENABLED
  }

  // 记录性能指标
  recordMetric(type, value, metadata = {}) {
    if (!this.isEnabled) return

    const metric = {
      type,
      value,
      timestamp: Date.now(),
      metadata
    }

    this.metrics.push(metric)

    // 限制记录数量
    if (this.metrics.length > MONITOR_CONFIG.MAX_RECORDS) {
      this.metrics.shift()
    }

    // 开发环境下打印
    if (process.env.NODE_ENV === 'development') {
      console.log(`性能指标 [${type}]:`, value, metadata)
    }
  }

  // 测量渲染时间
  measureRenderTime(componentName, renderFn) {
    if (!this.isEnabled) return renderFn()

    const startTime = performance.now()
    const result = renderFn()
    const endTime = performance.now()
    
    this.recordMetric(METRIC_TYPES.RENDER_TIME, endTime - startTime, {
      component: componentName
    })

    return result
  }

  // 测量API响应时间
  measureApiResponse(apiName, apiCall) {
    if (!this.isEnabled) return apiCall()

    const startTime = performance.now()
    
    return apiCall().then(result => {
      const endTime = performance.now()
      this.recordMetric(METRIC_TYPES.API_RESPONSE_TIME, endTime - startTime, {
        api: apiName
      })
      return result
    }).catch(error => {
      const endTime = performance.now()
      this.recordMetric(METRIC_TYPES.API_RESPONSE_TIME, endTime - startTime, {
        api: apiName,
        error: true
      })
      throw error
    })
  }

  // 测量图片加载时间
  measureImageLoad(imageSrc, loadPromise) {
    if (!this.isEnabled) return loadPromise

    const startTime = performance.now()
    
    return loadPromise.then(() => {
      const endTime = performance.now()
      this.recordMetric(METRIC_TYPES.IMAGE_LOAD_TIME, endTime - startTime, {
        image: imageSrc
      })
    }).catch(error => {
      const endTime = performance.now()
      this.recordMetric(METRIC_TYPES.IMAGE_LOAD_TIME, endTime - startTime, {
        image: imageSrc,
        error: true
      })
      throw error
    })
  }

  // 记录用户交互
  recordUserInteraction(action, target, duration = 0) {
    this.recordMetric(METRIC_TYPES.USER_INTERACTION, duration, {
      action,
      target
    })
  }

  // 获取性能报告
  getReport() {
    const report = {
      totalMetrics: this.metrics.length,
      uptime: Date.now() - this.startTime,
      averages: {},
      totals: {},
      errors: 0
    }

    // 计算平均值和总数
    const groupedMetrics = {}
    this.metrics.forEach(metric => {
      if (!groupedMetrics[metric.type]) {
        groupedMetrics[metric.type] = []
      }
      groupedMetrics[metric.type].push(metric.value)
      
      if (metric.metadata.error) {
        report.errors++
      }
    })

    Object.keys(groupedMetrics).forEach(type => {
      const values = groupedMetrics[type]
      report.averages[type] = values.reduce((a, b) => a + b, 0) / values.length
      report.totals[type] = values.reduce((a, b) => a + b, 0)
    })

    return report
  }

  // 清除数据
  clear() {
    this.metrics = []
    this.startTime = Date.now()
  }

  // 导出数据
  export() {
    return {
      metrics: this.metrics,
      report: this.getReport()
    }
  }
}

// 全局性能监控实例
const performanceMonitor = new PerformanceMonitor()

// 性能监控Hook
export const usePerformanceMonitor = (componentName) => {
  const renderStartTime = useRef(null)
  const interactionStartTime = useRef(null)

  // 开始测量渲染
  const startRenderMeasure = useCallback(() => {
    if (MONITOR_CONFIG.ENABLED) {
      renderStartTime.current = performance.now()
    }
  }, [])

  // 结束测量渲染
  const endRenderMeasure = useCallback(() => {
    if (MONITOR_CONFIG.ENABLED && renderStartTime.current) {
      const renderTime = performance.now() - renderStartTime.current
      performanceMonitor.recordMetric(METRIC_TYPES.RENDER_TIME, renderTime, {
        component: componentName
      })
      renderStartTime.current = null
    }
  }, [componentName])

  // 测量API调用
  const measureApi = useCallback((apiName, apiCall) => {
    return performanceMonitor.measureApiResponse(apiName, apiCall)
  }, [])

  // 测量图片加载
  const measureImageLoad = useCallback((imageSrc, loadPromise) => {
    return performanceMonitor.measureImageLoad(imageSrc, loadPromise)
  }, [])

  // 开始测量用户交互
  const startInteractionMeasure = useCallback((action, target) => {
    if (MONITOR_CONFIG.ENABLED) {
      interactionStartTime.current = {
        startTime: performance.now(),
        action,
        target
      }
    }
  }, [])

  // 结束测量用户交互
  const endInteractionMeasure = useCallback(() => {
    if (MONITOR_CONFIG.ENABLED && interactionStartTime.current) {
      const duration = performance.now() - interactionStartTime.current.startTime
      performanceMonitor.recordUserInteraction(
        interactionStartTime.current.action,
        interactionStartTime.current.target,
        duration
      )
      interactionStartTime.current = null
    }
  }, [])

  // 记录用户交互
  const recordInteraction = useCallback((action, target, duration = 0) => {
    performanceMonitor.recordUserInteraction(action, target, duration)
  }, [])

  // 获取组件性能报告
  const getComponentReport = useCallback(() => {
    const report = performanceMonitor.getReport()
    const componentMetrics = performanceMonitor.metrics.filter(
      metric => metric.metadata.component === componentName
    )
    
    return {
      ...report,
      componentMetrics,
      componentAverage: componentMetrics.length > 0 
        ? componentMetrics.reduce((a, b) => a + b.value, 0) / componentMetrics.length 
        : 0
    }
  }, [componentName])

  return {
    startRenderMeasure,
    endRenderMeasure,
    measureApi,
    measureImageLoad,
    startInteractionMeasure,
    endInteractionMeasure,
    recordInteraction,
    getComponentReport
  }
}

// 全局性能监控工具
export const useGlobalPerformanceMonitor = () => {
  // 获取全局报告
  const getGlobalReport = useCallback(() => {
    return performanceMonitor.getReport()
  }, [])

  // 清除所有数据
  const clearAllData = useCallback(() => {
    performanceMonitor.clear()
  }, [])

  // 导出所有数据
  const exportAllData = useCallback(() => {
    return performanceMonitor.export()
  }, [])

  // 启用/禁用监控
  const setEnabled = useCallback((enabled) => {
    performanceMonitor.isEnabled = enabled
  }, [])

  return {
    getGlobalReport,
    clearAllData,
    exportAllData,
    setEnabled
  }
}

// 性能监控装饰器（用于包装组件）
export const withPerformanceMonitor = (WrappedComponent, componentName) => {
  return (props) => {
    const { startRenderMeasure, endRenderMeasure } = usePerformanceMonitor(componentName)
    
    useEffect(() => {
      startRenderMeasure()
      return () => {
        endRenderMeasure()
      }
    }, [startRenderMeasure, endRenderMeasure])

    return <WrappedComponent {...props} />
  }
}

export default usePerformanceMonitor

